package com.oeandn.system.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oeandn.common.model.PageModel;
import com.oeandn.db.base.service.BaseService;
import com.oeandn.system.entity.InspectPathDetailDTO;
import com.oeandn.system.mapper.InspectPathMapper;
import com.oeandn.system.mapper.InspectPathPointMapper;
import com.oeandn.system.model.InspectPath;
import com.oeandn.system.model.InspectPathPoint;
import com.oeandn.system.model.InspectPoint;
import com.oeandn.system.model.InspectPointItem;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 巡检路线 服务实现类
 * </p>
 *
 * @author 饮水机管理员
 * @since 2022-08-09
 */
@Service
public class InspectPathService extends BaseService<InspectPathMapper, InspectPath> {

    @Resource
    InspectPathPointMapper inspectPathPointMapper;

    @Resource
    InspectPointService inspectPointService;

    @Resource
    InspectPointItemService inspectPointItemService;
    @Resource
    ApproveRecordService approveRecordService;


    /**
     * 获取表格数据
     *
     * @param inspectPath
     * @param pageModel
     * @return
     */
    public IPage<InspectPath> pageListByEntity(InspectPath inspectPath, PageModel pageModel) {
        QueryWrapper<InspectPath> queryWrapper = new QueryWrapper<>();

        if (StrUtil.isNotBlank(inspectPath.getPathType())) {
            queryWrapper.eq("a." + InspectPath.PATH_TYPE, inspectPath.getPathType());
        }
        if (StrUtil.isNotBlank(inspectPath.getPathName())) {
            queryWrapper.like("a." + InspectPath.PATH_NAME,
                    inspectPath.getPathName());
        }
        if (StrUtil.isNotBlank(inspectPath.getPathCode())) {
            queryWrapper.like("a." + InspectPath.PATH_CODE,
                    inspectPath.getPathCode());
        }
        if (StrUtil.isNotBlank(inspectPath.getInspectCycle())) {
            queryWrapper.like("a." + InspectPath.INSPECT_CYCLE,
                    inspectPath.getInspectCycle());
        }
        if (StrUtil.isNotBlank(inspectPath.getInspectOnDuty())) {
            queryWrapper.like("a." + InspectPath.INSPECT_ON_DUTY,
                    inspectPath.getInspectOnDuty());
        }

        if (StrUtil.isNotBlank(inspectPath.getApproveState())) {
            queryWrapper.like("b.approve_state",
                    inspectPath.getApproveState());
        }
        if (StrUtil.isNotBlank(inspectPath.getPathStatus())) {
            queryWrapper.like("a." + InspectPath.PATH_STATUS,
                    inspectPath.getPathStatus());
        }


        if (StrUtil.isNotBlank(inspectPath.getSequence())) {
            queryWrapper.like("a." + InspectPath.SEQUENCE,
                    inspectPath.getSequence());
        }
        if (StrUtil.isNotBlank(inspectPath.getVersion())) {
            queryWrapper.like("a." + InspectPath.VERSION,
                    inspectPath.getVersion());
        }
        if (StrUtil.isNotBlank(inspectPath.getSummarize())) {
            queryWrapper.like("a." + InspectPath.SUMMARIZE,
                    inspectPath.getSummarize());
        }


//        queryWrapper.and(w->{
//            for (int i = 1; i < macs.length; i++) {
//                w.or(DeviceInfo::getMac,macs[i]).or();
//            }
//            w.like(DeviceInfo::getMac,macs[0]);
//        });
        IPage page = new Page();
        page.setSize(pageModel.getSize());
        page.setCurrent(pageModel.getCurrent());
        return this.baseMapper.pageListByEntity(page, queryWrapper);
    }


    /**
     * 功能描述:巡检点改变巡检路线关联修改
     *
     * @param historyId 历史id
     * @param id        新id
     * @return {@link null}
     * @author GGW
     * @date 2022-08-10
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateInspectPathPoint(Long historyId, Long id) {

        List<InspectPathPoint> pathPointList =
                inspectPathPointMapper.selectList(new QueryWrapper<InspectPathPoint>().eq(
                        InspectPathPoint.POINT_ID, historyId));

        if (0 < pathPointList.size()) {

            inspectPathPointMapper.delete(new LambdaQueryWrapper<InspectPathPoint>().eq(InspectPathPoint::getPointId,
                    historyId));

            pathPointList.forEach(item -> {

                item.setPointId(id);
                inspectPathPointMapper.insert(item);
            });


        }


    }

    @Transactional(rollbackFor = Exception.class)
    public boolean saveInspectPath(InspectPath inspectPath) {
        boolean save = this.save(inspectPath);


        if (save) {
            //添加关联表
            inspectPath.getIds().forEach(item -> {
                InspectPathPoint pathPoint = new InspectPathPoint();
                pathPoint.setPathId(inspectPath.getId());
                pathPoint.setPointId(item);
                inspectPathPointMapper.insert(pathPoint);
            });

            //  审批
            return approveRecordService.saveApproveRecord(inspectPath.getDeptId(), inspectPath.getId(), "1", "0");
        }


        return false;
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean updateInspectPath(InspectPath inspectPath) {

        InspectPath Path = new InspectPath();

        Path.setPathType(inspectPath.getPathType());
        Path.setPathName(inspectPath.getPathName());
        Path.setPathCode(inspectPath.getPathCode());
        Path.setInspectCycle(inspectPath.getInspectCycle());
        Path.setInspectOnDuty(inspectPath.getInspectOnDuty());
        Path.setSequence(inspectPath.getSequence());
        Path.setVersion(inspectPath.getVersion());
        Path.setSummarize(inspectPath.getSummarize());
        Path.setHistoryCode(inspectPath.getHistoryCode());

        Path.setHistoryId(inspectPath.getId());
        Path.setDelFlag("2");

        Path.setCreateBy(inspectPath.getCreateBy());
        Path.setCreateDate(inspectPath.getCreateDate());
        Path.setDeptId(inspectPath.getDeptId());
        Path.setUpdateBy(inspectPath.getUpdateBy());
        Path.setUpdateDate(inspectPath.getUpdateDate());
        Path.setRemark(inspectPath.getRemark());
        Path.setCreateUserName(inspectPath.getCreateUserName());
        Path.setUpdateUserName(inspectPath.getUpdateUserName());

        boolean save = this.save(Path);


        if (save) {

            //添加关联表
            Path.getIds().forEach(item -> {
                InspectPathPoint pathPoint = new InspectPathPoint();
                pathPoint.setPathId(inspectPath.getId());
                pathPoint.setPointId(item);
                inspectPathPointMapper.insert(pathPoint);
            });


            //  审批
            return approveRecordService.saveApproveRecord(inspectPath.getDeptId(), Path.getId(), "1", "0");
        }

        return false;
    }

    /**
     * 功能描述:  审批通过调用
     *
     * @param id 业务id  路线id
     * @return {@link null}
     * @author GGW
     * @date 2022-08-11
     */
    @Transactional(rollbackFor = Exception.class)
    public void upd(Long id) {
        InspectPath path = this.getById(id);


        //删除关联表
        inspectPathPointMapper.delete(new LambdaQueryWrapper<InspectPathPoint>().eq(InspectPathPoint::getPathId,
                path.getHistoryId()));

        //修改主表
        path.setHistoryId(0L);
        path.setDelFlag("0");
        updateById(path);
    }

    public InspectPathDetailDTO getdetail(Long id) {

        InspectPathDetailDTO dto = new InspectPathDetailDTO();
        InspectPath byId = this.getById(id);

        if (!StringUtils.isEmpty(byId)) {
            dto.setPath(byId);
            List<InspectPath> list = this.list(new QueryWrapper<InspectPath>().eq(InspectPath.HISTORY_ID, id));
            dto.setPathHistory(list);

            List<InspectPathPoint> inspectPathPoints =
                    inspectPathPointMapper.selectList(new QueryWrapper<InspectPathPoint>().eq(InspectPathPoint.PATH_ID,id));

            List<Long> collect =
                    inspectPathPoints.stream().map(InspectPathPoint::getPointId).collect(Collectors.toList());
            if (0 < collect.size()) {
                List<InspectPointItem> list1 =
                        inspectPointItemService.list(new QueryWrapper<InspectPointItem>().in(InspectPointItem.ID,collect));
                dto.setItemList(list1);

                List<Long> collect1 =
                        list1.stream().map(InspectPointItem::getInspectPointId).collect(Collectors.toList());
                if (0 < collect1.size()) {

                    List<InspectPoint> list2 =
                            inspectPointService.list(new QueryWrapper<InspectPoint>().in(InspectPoint.ID,
                            collect1));
                    dto.setPoints(list2);

                }
            }
        }
        return dto;
    }

    public boolean startAndStop(Long id) {

        InspectPath path = getById(id);
        if ("0".equals(path.getPathStatus())) {
            path.setPathStatus("1");
        } else {
            path.setPathStatus("0");
        }

        return updateById(path);
    }
}
